<style src="../../style/statistics.css" scoped></style>
<template>
    <div class="containerTable">
        <Row class="divSearch">
            <!--搜索框-->
                <Col span="14" >
                    <label class="searchLabel">所属地区:</label>
                    <Select v-model="searchModel.AreaCode"  placeholder="请选择..." class="searchInput" @on-change="GetData()">
                        <Option :value="userInfo.AreaCode">{{(userInfo.AreaCode=='530000000000')?'全省':'全市（州）'}}</Option>
                        <Option :value="item.value" v-for="item in AreaList" :key="item.value">{{item.label}}</Option>
                    </Select>                              
                    <label class="searchLabel">填报年度:</label>
                    <Select v-model="searchModel.FillInYear" placeholder="全部" :label-in-value="true" @on-change="GetData()" class="searchInput">
                        <!-- <Option value="">全部</Option> -->
                        <Option :value="item.DictValue" v-for="item in CreateYearList" :key="item.DictValue">{{item.DictText}}</Option>
                    </Select>
                    <label class="searchLabel">水果种类:</label>
                    <Select v-model="searchModel.VarietyCode" placeholder="全部" :label-in-value="true" @on-change="VarietyChange" class="searchInput">    
                        <Option value="">全部</Option>                      
                        <Option :value="item.VarietyCode" v-for="item in VarietyList" :key="item.VarietyCode">{{item.Variety}}</Option>
                    </Select>
                    <Button icon="ios-search" type="ghost" @click="GetData()">查询</Button>
                </Col>                     
                <Col span="10" class="searchRight">                                             
                    <RadioGroup v-model="currentButton" @on-change="changeButton" type="button"  >
                        <Radio label="listShow" title="列表">列表<Icon type="ios-paper" size="10"></Icon></Radio>                            
                        <Radio label="barShow" title="柱状图">柱状图<Icon type="stats-bars" size="10"></Icon></Radio>
                        <Radio label="mapShow" title="地图">地图<Icon type="android-map" size="10"></Icon></Radio>                            
                    </RadioGroup>                    
              </Col>                              
            </Row>
            <Row class="divSearch">
                <Col span="24" class="searchRight">
                <!-- <Button type="success"  class="searchButtonLeft"  @click="toAlertCheckResult()" >数据检测</Button>  -->
                    <label class="searchLabel">请选择导出类型:</label>
                    <Select v-model="searchModel.downType"  :label-in-value="true"  class="searchInput" > 
                        <Option value="1">导出地区列表</Option>                    
                        <Option value="2">导出类型列表</Option>
                    </Select>
                    <Button style="margin-left:10px;" type="primary" v-show="listShow" @click="Download(searchModel.AreaCode)">导出列表</Button> 
                </Col>                                            
            </Row>                
            <Row  v-show="listShow" class="divStatis">
            <!-- 列表-->
                <table class="statisTable">
                    <!-- <caption>{{getVariety()}}年度面积产量统计</caption> -->
                    <thead>
                        <tr>
                            <th style="width:210px" rowspan="2">{{(searchModel.VarietyCode=="")?'种类':'地区'}}</th>
                            <th rowspan="2">全年累计面积（亩）</th>
                            <th rowspan="2">全年累计产量（吨）</th>
                            <th rowspan="2">平均亩产（吨/亩）</th>
                            <th colspan="4">其中（亩）</th>
                        </tr>
                        <tr>
                            <th>当年新植果园面积</th>
                            <th>树龄5年以下果园面积</th>
                            <th>树龄5-20年果园面积</th>
                            <th>树龄20年以上果园面积</th>
                        </tr>
                    </thead>
                    <tbody :style="{height:clientHeight+'px'}">
                        <tr v-for="(dataModel,index) in datalist" :key="index" :style="rowStyle(index,datalist.length)">
                            <td v-if="dataModel.ParentCode" v-show="searchModel.VarietyCode==''" style="width:210px;text-align:right;">{{dataModel.Variety}}</td> 
                            <td v-else v-show="searchModel.VarietyCode==''" style="font-weight:bold;text-align:center;width:210px">{{dataModel.Variety}}</td>
                            <td v-show="searchModel.VarietyCode!=''" style="text-align:center;width:210px;">{{dataModel.AreaName}}</td>
                            <td>{{(dataModel.GrandArea)?FormatBigNum(dataModel.GrandArea.toFixed(1)):''}}</td>
                            <td>{{(dataModel.CumYield)?FormatBigNum(dataModel.CumYield.toFixed(1)):''}}</td>
                            <td>{{(dataModel.AvgMuYield)?dataModel.AvgMuYield.toFixed(1):''}}</td>
                            <td>{{(dataModel.NewArea)?FormatBigNum(dataModel.NewArea.toFixed(1)):''}}</td>
                            <td>{{(dataModel.FOrchard)?FormatBigNum(dataModel.FOrchard.toFixed(1)):''}}</td>
                            <td>{{(dataModel.FTOrchard)?FormatBigNum(dataModel.FTOrchard.toFixed(1)):''}}</td>
                            <td>{{(dataModel.TOrchard)?FormatBigNum(dataModel.TOrchard.toFixed(1)):''}}</td>
                        </tr>
                    </tbody>
                </table>
         </Row>
         <Row v-show="barShow">
            <!--柱状图-->
            <div  id="divBar" style="border:1px solid #D7DDE4;">柱状图</div>
        </Row>
        <Row  v-show="mapShow" >
            <!--地图展示-->
            <div id="divMap"  style="border:1px solid #D7DDE4; ">地图</div>
        </Row>
    </div>
</template>
<script>
import echarts from "echarts";
export default {
    data() {
        return {
            chartStyle:{height:(window.innerHeight - 220)+'px',width:(window.innerWidth - 250)+'px'},
            currentButton:'listShow',
            listShow:true,//列表显示控制器
            barShow:false,//饼图显示控制器
            mapShow:false,//地图显示控制器            
            userInfo: this.GetlocaStorage("fruuserinfo"),            
            AreaList: this.SearchAreaList(this.GetlocaStorage("fruuserinfo").AreaCode),//所属行政区划数组,           
            CreateYearList: this.GetGroupDict("ReportYear"),//周期
            CycleList: this.GetGroupDict("ReportCycle"),// \
            VarietyList:[] , 
            datalist:[],  
            fruitName:'水果' ,
            //柱状图数据
            xlist:[],
            GrandArealist:[],
            CumYieldlist:[],
            AvgMuYieldlist:[],
            NewArealist:[],
            FOrchardlist:[],
            FTOrchardlist:[],
            TOrchardlist:[],
            barList:[],
            //地图数据
            mGrandArealist:[],
            mCumYieldlist:[],
            mAvgMuYieldlist:[],
            mNewArealist:[],
            mFOrchardlist:[],
            mFTOrchardlist:[],
            mTOrchardlist:[],
            mapList:[],
            echartsItem: ["全年累计面积","全年累计产量","平均亩产", "当年新建果园面积","树龄5年以下果园面积","树龄5-20年果园面积","树龄20年以上果园面积"],
            //查询模型：根据需求删除不不要查询条件
            searchModel: {
                ReportCode: 'FruProSurvey',
                FillInYear: new Date().getFullYear()+"",                
                AreaCode: this.GetlocaStorage("fruuserinfo").AreaCode,
                VarietyCode:'',
                Variety:'',
                downType:'1',
                PageNumber: 1, PageSize: 20
            },
            pageSizeOpts: [20, 40, 50],//默认分页最大设置
            datas: {},//table数据对象
            dataIds: [],
            ctx: this,//table数据上下文
            columnsList: [],
            clientHeight: window.innerHeight - 260,//表格默认高度
        }
    },
    mounted() {
        //table高度计算方法
        const that = this;
        window.onresize = () => {
            return (() => {
                that.clientHeight = window.innerHeight - 260;
            })()
        };
    },
    methods: {
        rowStyle(index,length){  
            let striprow ={ backgroundColor: '#ebf7ff'};      
            if(index==(length-1)){       
                return {
                    backgroundColor: '#f9c912'
                    }
            }
            else if(index%2 !=0){
                return striprow;
            }
            else{        
                return 
            }
        },
        changeButton(n){
            if(n=="listShow")
            {
                this.listShow=true;//显示列表
                this.barShow=false;
                this.mapShow=false;
            }
            else if(n=="barShow")
            {
                this.listShow=false;
                this.barShow=true;//显示饼图
                this.mapShow=false;
                this.showBar();
            }
             else if(n=="mapShow")
            {
                this.listShow=false;
                this.barShow=false;//显示地图
                this.mapShow=true;
                //  this.getStatsData();   //获取地区统计数据  
                //this.showMap();
                if(!this.searchModel.VarietyCode)
                this.searchModel.VarietyCode='sum';
            }
            else{
                 this.listShow=true;//默认显示列表
                 this.barShow=false;
                 this.mapShow=false;
            }
        },
    showBar() {
        var self = this;
        //显示柱状图
        var self=this;
        var containerBar=document.getElementById('divBar');
        var containerTable=document.getElementsByClassName('ivu-col ivu-col-span-4');
        //用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
        var resizeContainerBar = function () {
           // containerTable[0].clientWidth 左侧菜单栏的宽度
            containerBar.style.width = (window.innerWidth- containerTable[0].clientWidth-20)+'px';
            containerBar.style.height = (window.innerHeight-250)+'px';
        };
        //设置容器高宽
        resizeContainerBar();
        var myBar = myEcharts.init(containerBar, 'shine');
        var BarName=this.searchModel.FillInYear+'年(二)'+self.CurrentAreaName + self.fruitName+ '全年生产情况表';
        self.barList = [];
        self.barList.push(self.GrandArealist,self.CumYieldlist,self.AvgMuYieldlist,self.NewArealist,self.FOrchardlist,self.FTOrchardlist,self.TOrchardlist);
        var optionBar = self.GetBarOption(BarName,self.xlist,self.echartsItem,self.barList);
        myBar.setOption(optionBar);
        window.onresize = function () {
            //重置容器高宽
            resizeContainerBar();
            myBar.resize();
        };
    },
    showMap(){
        //******************显示地图
        var self=this;
        var mapType;
        //判断当前用户是否为省级账号
        if(self.userInfo.AreaCode=="530000000000")
        {
            // self.isProvince=true;
            mapType=self.searchModel.AreaCode;
        }
        else{
            mapType=self.userInfo.AreaCode;
        }
        var containerMap=document.getElementById('divMap');
        var containerTable=document.getElementsByClassName('ivu-col ivu-col-span-4');
        // //用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
        var resizeContainerMap = function () {
            //containerTable[0].clientWidth 左侧菜单栏的宽度
            containerMap.style.width = (window.innerWidth- containerTable[0].clientWidth-20)+'px';
            containerMap.style.height = (window.innerHeight-230)+'px';
        };
        //设置容器高宽
        resizeContainerMap();

        var myMap = myEcharts.init(containerMap, 'shine');
        var MapName=this.searchModel.FillInYear+'年(二)'+self.CurrentAreaName+ self.fruitName+'全年生产情况表';
        
        var GeoData=self.GetGeoData(mapType); 
        self.mapList = [];
        self.mapList.push(self.mGrandArealist,self.mCumYieldlist,self.mAvgMuYieldlist,self.mNewArealist,self.mFOrchardlist,self.mFTOrchardlist,self.mTOrchardlist);
        var optionMap = self.GetMapOption(MapName,GeoData,mapType,self.echartsItem,self.mapList);
        myMap.setOption(optionMap);
        //用于使chart自适应高度和宽度
        window.onresize = function () {
            //重置容器高宽
            resizeContainerMap();
            myMap.resize();
        };
    },
        getVarietyDic(){
            var self = this;            
            this.$http.get('FruProSurvey/GetVarietyDic',).then(function(res){
                if(res.data.status==1){
                    self.VarietyList = res.data.model;
                }
                else{
                    self.$Modal.error({title:'提示信息',content:res.data.message});
                }
            })
        },
         Download(){  
          //this.getVariety();          
            window.open(this.$http.defaults.baseURL + "FruProSurvey/GetStatisExcel?FillInYear="  + this.searchModel.FillInYear + "&&AreaCode=" + this.userInfo.AreaCode+
            "&&DownType="+this.searchModel.downType);
        },
        getListData(){
            var self = this;
            let model = new Object();
            model.AreaCode = this.searchModel.AreaCode;
            model.FillInYear = this.searchModel.FillInYear;
            model.VarietyCode = this.searchModel.VarietyCode; 
            self.xlist = [];
            self.GrandArealist = [];
            self.CumYieldlist = [];
            self.AvgMuYieldlist = [];
            self.NewArealist = [];
            self.FOrchardlist = [];
            self.FTOrchardlist = [];
            self.TOrchardlist = [];    
            self.mGrandArealist = [];
            self.mCumYieldlist = [];
            self.mAvgMuYieldlist = [];
            self.mNewArealist = [];
            self.mFOrchardlist = [];
            self.mFTOrchardlist = [];
            self.mTOrchardlist = [];           
            this.$http.get('FruProSurvey/GetStatisListData',{params:model}).then(function(res){
                if(res.data.status==1){
                    self.datalist = res.data.model;
                    self.CurrentAreaName=self.datalist[self.datalist.length-1].AreaName=="合计"||!self.datalist[self.datalist.length-1].AreaName?'云南省':self.datalist[self.datalist.length-1].AreaName;
                        for(let i = 0;i<self.datalist.length-1;i++){
                            let item = self.datalist[i];
                            //柱状图
                            if(self.searchModel.VarietyCode == ""){
                                self.xlist.push(item.Variety);
                            }else{
                                self.xlist.push(item.AreaName);
                            }  
                            self.GrandArealist.push(item.GrandArea);
                            self.CumYieldlist.push(item.CumYield);
                            self.AvgMuYieldlist.push(item.AvgMuYield);
                            self.NewArealist.push(item.NewArea);
                            self.FOrchardlist.push(item.FOrchard);
                            self.FTOrchardlist.push(item.FTOrchard);
                            self.TOrchardlist.push(item.TOrchard);  
                            //地图
                            self.mGrandArealist.push({'name':item.AreaName,'value':item.GrandArea});
                            self.mCumYieldlist.push({'name':item.AreaName,'value':item.CumYield});
                            self.mAvgMuYieldlist.push({'name':item.AreaName,'value':item.AvgMuYield});
                            self.mNewArealist.push({'name':item.AreaName,'value':item.NewArea});
                            self.mFOrchardlist.push({'name':item.AreaName,'value':item.FOrchard});
                            self.mFTOrchardlist.push({'name':item.AreaName,'value':item.FTOrchard});
                            self.mTOrchardlist.push({'name':item.AreaName,'value':item.TOrchard});  
                        }      
                    self.showBar();
                    self.showMap();
                }
                else{
                    self.$Modal.error({title:'提示信息',content:res.data.message});
                }
            })
        },
        GetData(){
            this.getListData();
        },
         VarietyChange(obj){
          var lable = obj.label;
          this.fruitName = (lable=='全部'||lable=='合计')?'水果':lable;
          this.GetData();
        },
         //数据检测
    checkData(){
        let templist = this.datalist;
        let isOk = true;//数据无误
        let message = '';
        let sumObj = templist[templist.length-1];//合计栏数据
        let totalModel = new Object();
        totalModel.GrandArea = 0;
        totalModel.CumYield = 0;
        //totalModel.AvgMuYield = "";
        totalModel.NewArea = 0;
        totalModel.FOrchard = 0;
        totalModel.FTOrchard = 0;
        totalModel.TOrchard = 0;  
        for(let i = 0;i < templist.length;i++){
            let item  = templist[i];
            let parentModel = new Object();
            parentModel.GrandArea = 0;
            parentModel.CumYield = 0;
            parentModel.NewArea = 0;
            parentModel.FOrchard = 0;
            parentModel.FTOrchard = 0;
            parentModel.TOrchard = 0;  
            parentModel.hasChild = false; 
            for(let j = 0;j < templist.length;j++){
                let sonItem = templist[j];
                if(sonItem.ParentCode == item.VarietyCode){
                parentModel.hasChild = true;
                if(sonItem.GrandArea){
                    parentModel.GrandArea += sonItem.GrandArea;
                }
                if(sonItem.CumYield){
                    parentModel.CumYield += sonItem.CumYield;
                }
                if(sonItem.NewArea){
                    parentModel.NewArea += sonItem.NewArea;
                }
                if(sonItem.FOrchard){
                    parentModel.FOrchard += sonItem.FOrchard;
                }
                if(sonItem.FTOrchard){
                    parentModel.FTOrchard += sonItem.FTOrchard;
                }
                if(sonItem.TOrchard){
                    parentModel.TOrchard += sonItem.TOrchard;
                }
            }
        }
        if(parentModel.hasChild){        
            if(item.GrandArea && parentModel.GrandArea > item.GrandArea){         
                isOk = false;
                message += item.Variety+'的全年累计面积不能小于其子项之和！</br>';        
            }
            if(item.CumYield && parentModel.CumYield > item.CumYield){
                isOk = false;
                message += item.Variety+'的全年累计产量不能小于其子项之和！</br>';
            }
            if(item.NewArea && parentModel.NewArea > item.NewArea){
                isOk = false;
                message += item.Variety+'的本年新建果园面积不能小于其子项之和！</br>';
            }
            if(item.FOrchard && parentModel.FOrchard > item.FOrchard){
                isOk = false;
                message += item.Variety+'的树龄5年以下面积不能小于其子项之和！</br>';
            }
            if(item.FTOrchard && parentModel.FTOrchard > item.FTOrchard){
                isOk = false;
                message += item.Variety+'的树龄5-20年面积不能小于其子项之和！</br>';
            } 
            if(item.TOrchard && parentModel.TOrchard > item.TOrchard){
                isOk = false;
                message += item.Variety+'的树龄20年以上面积不能小于其子项之和！</br>';
            }    
        } 
        if((item.GrandArea - (item.NewArea*1+item.FTOrchard*1+item.FOrchard*1+item.TOrchard*1))<-1||(item.GrandArea - (item.NewArea*1+item.FTOrchard*1+item.FOrchard*1+item.TOrchard*1))>1){
            isOk = false;
            message += item.Variety+'的全年累计面积不等于新植面积、树龄5年以下、5-20年、20年以上面积之和！</br>'
        }   
        if(item.VarietyCode !='sum'&& !item.ParentCode){        
            if(item.GrandArea){
                totalModel.GrandArea += item.GrandArea;
            }
            if(item.CumYield){
                totalModel.CumYield += item.CumYield;
            }
            if(item.NewArea){
                totalModel.NewArea += item.NewArea;
            }
            if(item.FOrchard){
                totalModel.FOrchard += item.FOrchard;
            }
            if(item.FTOrchard){
                totalModel.FTOrchard += item.FTOrchard;
            }
            if(item.TOrchard){
                totalModel.TOrchard += item.TOrchard;
            }
        }
    }
        if(sumObj.GrandArea && (totalModel.GrandArea-sumObj.GrandArea < -1||totalModel.GrandArea-sumObj.GrandArea > 1)){       
            isOk = false;
            message += '合计栏的全年累计面积计算错误！</br>';
        }
        if(sumObj.CumYield && (totalModel.CumYield-sumObj.CumYield < -1||totalModel.CumYield-sumObj.CumYield >1)){
            isOk = false;
            message += '合计栏的全年累计产量计算错误！</br>';
        }
        if(sumObj.NewArea && (totalModel.NewArea-sumObj.NewArea < -1||totalModel.NewArea-sumObj.NewArea >1)){
            isOk = false;
            message += '合计栏的新建果园面积计算错误！</br>';
        }
        if(sumObj.FOrchard && (totalModel.FOrchard-sumObj.FOrchard < -1||totalModel.FOrchard-sumObj.FOrchard >1)){
            isOk = false;
            message += '合计栏的树龄5年以下面积计算错误！</br>';
        }
        if(sumObj.FTOrchard && (totalModel.FTOrchard-sumObj.FTOrchard <-1||totalModel.FTOrchard-sumObj.FTOrchard >1)){
            isOk = false;
            message += '合计栏的树林个5-20年面积计算错误！</br>';
        }
        if(sumObj.TOrchard && (totalModel.TOrchard-sumObj.TOrchard <-1||totalModel.TOrchard-sumObj.TOrchard >1)){
            isOk = false;
            message += '合计栏的树龄20年以上面积计算错误！</br>';
        }
        if(isOk){
            message += '数据检测无误！';
        }
        return message;
    },
    toAlertCheckResult(){ 
        var message  = this.checkData();   
        this.$Modal.warning({
        title:'提示信息',
        content:message
      });
    },
        currentYear() {
            let year = new Date().getFullYear();
            let month = new Date().getMonth();
            if (month > 1) {
                this.searchModel.FillInYear = year.toString();
            } else {
                this.searchModel.FillInYear = (year - 1).toString();
                }
        }
        
    },
    //创建Vue页面方法
    created: function () {
        this.currentYear();
        this.getVarietyDic();
        this.GetData();
    },
    watch: {
        //需要监听的在此处新增监听对象
    }
}
</script>
